<?php

class Notes extends Onecore_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model("objects_model");
        $this->_moduleName = utf8_encode("Modulo modulos_model");
        $this->_moduleDescription = utf8_encode("Description") . $this->_moduleName;
        $this->_modelInstance = $this->objects_model;
    }
    public function save(){
        $cfg = (object)$this->config->item('defaultCfg');
        $valid = true;
        $success = false;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " creado en forma exitosa";
        $errorList = array();
        
        $objects_id = $this->input->post('objects_id');
        $content = $this->input->post('content');
        
        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        $now = date('Y-m-d H:i:s');
        $object = $this->_modelInstance->getByid($objects_id);

        if(!empty($object[0]))  {
            $object = $object[0];
            $edit = false;
            $query = new stdClass();
            $query->conditions = new stdClass();
            $query->conditions->parent = $object->id;
            $query->conditions->type_objects_id = $cfg->type_object_note;
            $note = $this->_modelInstance->listEntities($query);
            
            $data = array(
                "data" => array(
                    'users_id'=>$uid,
                    'content' => $content
                )
            );
            //si ya posee nota la actualizamos, sino creamos
            if(count($note['items'])>0)
            {
                $edit = true;
                $note = $note['items'][0];
                $data['id'] = array("id"=>$note->id);
                $data['data']['umodified'] = $userEmail;
                $data['data']['dmodified'] = $now;
                $data['data']['version'] = $note->version+1;
            }
            else{
//                log_message("error","no se encontraron notas");
                $data['data']['users_id'] = $uid;
                $data['data']['ucreated'] = $userEmail;
                $data['data']['parent'] = $object->id;
                $data['data']['type_objects_id'] = $cfg->type_object_note;
                $data['data']['version'] = 1;
            }

            if ($this->_modelInstance->save($data, $edit)) {
                $success = true;
            } else {
                $mensaje = "El objeto Nota no pudo ser guardado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
        }
        else{
            $mensaje = "El objeto Tema [$objects_id] no existe.";
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    
}